package com.hanson.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.api_bean.ScoreOrderRequest;
import com.hanson.common.bean.CartParam;
import com.hanson.common.bean.OrderMergeBean;
import com.hanson.common.bean.OrderSubmitParam;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.*;
import com.hanson.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "订单管理")
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private UserService userService;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private OrderRefundService orderRefundService;

    @ApiOperation(value = "新增普通订单")
    @RequestMapping(value = "/addNormal", method = RequestMethod.POST)
    public ResultMessage add(@RequestBody OrderBean orderBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.addOrder(openId, orderBean));
        resultMessage.setMsg("新增订单成功！");
        return resultMessage;
    }

    @ApiOperation(value = "新增积分订单")
    @RequestMapping(value = "/addScoreOrder", method = RequestMethod.POST)
    public ResultMessage addScoreOrder(@RequestBody ScoreOrderRequest ScoreOrderRequest, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.addScoreOrder(openId, ScoreOrderRequest));
        resultMessage.setMsg("新增积分订单成功！");
        return resultMessage;
    }

    @ApiOperation(value = "新增秒杀订单")
    @RequestMapping(value = "/addSkillOrder", method = RequestMethod.POST)
    public ResultMessage addSkillOrder(@RequestBody SeckillGoodsBean seckillGoodsBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.addSkillOrder(openId, seckillGoodsBean));
        resultMessage.setMsg("新增秒杀订单成功！");
        return resultMessage;
    }

    @ApiOperation(value = "新增拼团订单")
    @RequestMapping(value = "/addGroupOrder", method = RequestMethod.POST)
    public ResultMessage addGroupOrder(@RequestBody GroupGoodsBean groupGoodsBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.addGroupOrder(openId, groupGoodsBean));
        resultMessage.setMsg("新增拼团订单成功！");
        return resultMessage;
    }

    @ApiOperation(value = "新增购物车订单")
    @RequestMapping(value = "/addCartOrder", method = RequestMethod.POST)
    public ResultMessage addCartOrder(@RequestBody CartParam cartParam, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.addCartOrder(openId, cartParam));
        resultMessage.setMsg("新增购物车订单成功！");
        return resultMessage;
    }

    @ApiOperation(value = "获取订单确认页面数据")
    @RequestMapping(value = "/getOrderSubmitData/{orderSeq}", method = RequestMethod.GET)
    public ResultMessage getOrderSubmitData(HttpServletRequest request, @PathVariable(value = "orderSeq") String orderSeq) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        JSONObject returnObj = new JSONObject();

        List<UserAddresBean> list = userAddressService.selectByOpenId(openId);
        UserAddresBean selectBean = null;
        if (CollectionUtils.isNotEmpty(list)) {
            for (UserAddresBean userAddresBean : list) {
                if (userAddresBean.getIsDefault() == 1) {
                    selectBean = userAddresBean;
                    break;
                }
            }
        }
        returnObj.put("orderSeq", orderSeq);
        ModelMap modelMap = new ModelMap();
        returnObj.put("goods", orderService.selectOrderGoodsByOrderId(orderSeq, modelMap));
        returnObj.put("totalPrice", modelMap.get("totalPrice"));
        returnObj.put("totalNum", modelMap.get("totalNum"));
        returnObj.put("orderType", modelMap.get("orderType"));
        returnObj.put("totalScore", modelMap.get("totalScore"));
        returnObj.put("totalMoney", modelMap.get("totalMoney"));
        returnObj.put("address", list);
        returnObj.put("selectAddress", selectBean);
        returnObj.put("coupons", couponsService.getAvailableCoupons(openId, returnObj.getString("totalPrice")));
        returnObj.put("user", userService.selectByOpenId(openId));
        resultMessage.setData(returnObj);
        resultMessage.setMsg("获取数据成功！");
        return resultMessage;
    }

    @ApiOperation(value = "获取售后记录")
    @RequestMapping(value = "/listOrderRefund/{page}/{limit}", method = RequestMethod.GET)
    public ResultMessage listOrderRefund(HttpServletRequest request, @PathVariable Integer page, @PathVariable Integer limit) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        Page<OrderRefundBean> pageInfo = new Page<>(page, limit);
        resultMessage.setData(orderRefundService.listOrderRefund(pageInfo, openId));
        resultMessage.setMsg("获取售后记录成功！");
        return resultMessage;
    }


    @ApiOperation(value = "订单确认列表",notes = "修改地址,选择积分、余额、优惠卷、算钱")
    @RequestMapping(value = "/updateExtInfo", method = RequestMethod.POST)
    public ResultMessage updateExtInfo(@RequestBody OrderSubmitParam orderSubmitParam, HttpServletRequest request) {
        log.info("updateExtInfo orderSubmitParam:{}", JSON.toJSONString(orderSubmitParam));
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(orderService.updateAddressInfo(orderSubmitParam, openId));
        resultMessage.setMsg("修改地址信息成功！");
        return resultMessage;
    }

    @ApiOperation(value = "取消订单")
    @RequestMapping(value = "/delete/{orderSeq}", method = RequestMethod.POST)
    public ResultMessage delete(@PathVariable String orderSeq){
        orderService.deleteOrder(orderSeq);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("操作成功！");
        return resultMessage;
    }

    @ApiOperation(value = "确认订单")
    @RequestMapping(value = "/confirm/{orderSeq}", method = RequestMethod.POST)
    public ResultMessage confirm(@PathVariable String orderSeq)  {
        orderService.updateStatus(4, orderSeq);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("操作成功！");
        return resultMessage;
    }

    @ApiOperation(value = "完成订单")
    @RequestMapping(value = "/finsish/{orderSeq}", method = RequestMethod.POST)
    public ResultMessage finsish(@PathVariable String orderSeq){
        orderService.finishOrder(orderSeq);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("操作成功！");
        return resultMessage;
    }

    @ApiOperation(value = "个人页面统计订单个数", notes = "待付款:1 待发货:2 待收货:3 待评价:4 已完成:5 待拼团:6")
    @RequestMapping(value = "/groupByStatus", method = RequestMethod.GET)
    public ResultMessage groupByStatus(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        List<Map<Integer, Integer>> staticMap = orderService.groupByStatus(openId);
        Map<String, Integer> dataMap = new HashMap<>();
        dataMap.put("status1", 0);
        dataMap.put("status2", 0);
        dataMap.put("status3", 0);
        dataMap.put("status4", 0);
        dataMap.put("status5", 0);
        dataMap.put("status6", 0);
        if (CollectionUtils.isNotEmpty(staticMap)) {
            staticMap.stream().forEach(c -> {
                dataMap.put("status" + c.get("STATUS"), c.get("num"));
            });
        }
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("查询！");
        resultMessage.setData(dataMap);
        return resultMessage;
    }

    @ApiOperation(value = "根据订单状态查询订单列表", notes = "待付款:1 待发货:2 待收货:3 待评价:4 已完成:5 待拼团:6")
    @RequestMapping(value = "/myOrder/{status}", method = RequestMethod.GET)
    public ResultMessage myOrder(HttpServletRequest request, @PathVariable(value = "status") String status) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ModelMap modelMap = new ModelMap();
        List<OrderMergeBean> orderMergeBeanList = orderService.selectByOpenId(openId, status, modelMap);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("查询成功！");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", orderMergeBeanList);
        jsonObject.put("totalOrder", modelMap.get("totalOrder"));
        jsonObject.put("totalMoney", modelMap.get("totalMoney"));
        jsonObject.put("groupOrder", modelMap.get("groupOrder"));
        jsonObject.put("status", modelMap.get("status"));
        resultMessage.setData(jsonObject);
        return resultMessage;
    }

    @ApiOperation(value = "查询订单详情")
    @RequestMapping(value = "/orderDetail/{orderSeq}", method = RequestMethod.GET)
    public ResultMessage orderDetail(HttpServletRequest request, @PathVariable String orderSeq) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ModelMap modelMap = new ModelMap();
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("查询成功！");
        resultMessage.setData(orderService.selectMergeDetail(orderSeq));
        return resultMessage;
    }


}
